<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 4/13 0013
 * Time: 14:32
 */

namespace app\api\controller;


use think\Cache;
use think\Controller;

class Meituan extends Controller
{

    /**
     * Meituan constructor.
     * Signkey 签名key
     * develperid 开发者ID
     */
    public function __construct() {
        parent::__construct();
        define("SIGNKEY", 'r2wmwbjl2rmjftsh');
        define("DEVELOPERID","100435");
    }

    /**
     * 绑定门店
     * @return \think\response\Json
     */
    public function addshop(){
        $ePoiId =model("meituan")->ePoiId();
        Cache::set($ePoiId,request()->post("shopid"),3600);
        $url = "http://fuzzyy.wicp.net/index.php/api/meituanheart/calback";
        $callback = urlencode($url);
        $url = "https://open-erp.meituan.com/storemap?developerId=".DEVELOPERID."&businessId=2&ePoiId=$ePoiId&signKey=".SIGNKEY."&callbackUrl=$callback";
        return json(["code"=>1,"data"=>$url,"msg"=>"获取成功"]);
    }

    /**
     *  绑定团购门店
     * @return \think\response\Json
     */
    public function Tuanaddshop(){
        if(!request()->post("shopid")){
            return json(["code"=>0,"data"=>"","msg"=>"获取成功"]);
        }
        $res=model("meituan")->where("shopid",request()->post("shopid"))->find();
        if(!isset($res["epoiid"])){
            return json(["code"=>0,"data"=>"","msg"=>"no shop"]);
        }
        $url = "http://fuzzyy.wicp.net/index.php/api/meituanheart/Tuanaddshopcalback";
        $callback =urlencode($url);
        $url = "https://open-erp.meituan.com/storemap?developerId=".DEVELOPERID."&businessId=1&ePoiId={$res['epoiid']}&signKey=".SIGNKEY."&callbackUrl=$callback";
        return json(["code"=>1,"data"=>$url,"msg"=>"获取成功"]);
    }

    /**
     * @deprecated
     */
    public function CheckTuan(){
        $res = model('Meituan')
            ->where("e_meituan.typeof=2")
            ->join('e_xcsstore ON e_xcsstore.stationno = e_meituan.epoiid')
            ->select();
        echo '<div class="mt-20">
    <table style="margin:50px auto;width:900px;" cellspacing="0" cellpadding="0" border="1">';
        foreach ($res as $k => $val) {
            $url="https://open-erp.meituan.com/coupon?signKey=".SIGNKEY."&appAuthToken=".$val['token'];
            echo "<tr><th height='40'>店名：";
            echo "<th/>".$val['stationname']."<th>";
            echo "门店编号：".$val['epoiid'];
            echo "<th/><a href=$url>团购用卷查询</a><tr>";
        }
        echo "</div></table><style>tr:hover {background: #ccc;}</style>";
    }

    /**
     * @deprecated
     */
    public function shop(){
        $Meituansql = model('Meituan');
        $meituan=$Meituansql->select();
        foreach ($meituan as $key => $value) {
            $ePoiId = $value['epoiid'];
            $token = $value['token'];
            $time = time();
            $url = "http://api.open.cater.meituan.com/waimai/poi/queryPoiInfo?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiIds=$ePoiId";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json = curl_get($url);
            $data[] = json_decode($json,true);
        }
        foreach ($data as $key => $value) {
            if(isset($value['error'])){
                unset($data[$key]);//清除错误门店信息
            }
        }
        $xcsstore = model('xcsstore');
        foreach ($data as $k => $value) {
            foreach ($value as $vals) {
                foreach ($vals as $key => $val) {
                    if($val['isOpen']=='1'){}else{$val['isOpen']='2';}
                    $stationno=$val['ePoiId'];
                    $sqlres=array(
                        "stationno"=>$stationno,        //门店编号
                        "stationname"=>$val['name'],            //门店名称
                        "stationaddress"=>$val['address'],  //门店地址
                        "contacts"=>$val['name'],           //联系人
                        "phone"=>$val['phone'],             //联系电话
                        "storeact"=>$val['noticeInfo'],     //门店活动
                        "yn"=>$val['isOpen'],               //运营状态
                        "storesou"=>'2',                    //分类->美团2
                        "createtime"=>time(),               //最后更新时间
                    );
                    $res=$check=$xcsstore->where("stationno='$stationno'")->count();
                    if($check){
                        $res=$xcsstore->where("stationno='$stationno'")->save($sqlres);
                    }else{
                        $res=$xcsstore->data($sqlres)->save();
                    }
                }
            }
        }
        if($res){
            $this->queryCatList();
            echo 1;
        }else{
            echo 2;
        }
    }

    /**
     * @deprecated
     */
    public function dishes(){
        $jdgoods = model("jdgoods");
        $Meituan = model('Meituan');
        $meituanArr = $Meituan->select();
        foreach ($meituanArr as $key => $value) {
            $ePoiId = $value['epoiid'];
            $token = $value['token'];
            $time = time();
            $url = "http://api.open.cater.meituan.com/waimai/dish/queryBaseListByEPoiId?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiId=$ePoiId";
            $signKey = model("meituan")->SignKey($url);
            $url=$url."&sign=".$signKey;
            $json=curl_get($url);
            $data=json_decode($json,true);
            foreach ($data as $key => $value) {
                if(isset($value['error_type'])){
                    unset($data[$key]);//删除错误签名返回数据
                }
            }
            foreach ($data as $key => $value) {
                foreach ($value as $k => $v) {
                    $skuid=$v['dishId'];
                    foreach ($v['waiMaiDishSkuBases'] as $ke => $vale) {
                        $dishName=$vale['dishSkuName'];
                        $dishSkuId=$vale['dishSkuId'];
                        $sqlres=array(
                            "skuid"=>$skuid,//商品编号，美团方菜品id
                            "skuname"=>$dishName,//商品名称
                            "skuprice"=>$vale['price'],//商品价格
                            "shopid"=>$ePoiId,//商品所属门店id
                            "baidu_dish_id"=>$dishSkuId,//美团方菜品id
                            "createtime"=>time(),//商品更新时间
                            "goodsasc"=>'2',//商品所属类型->美团外卖
                        );
                        $check=$jdgoods->where("baidu_dish_id='$dishSkuId'")->count();
                        if($check){
                            $res=$jdgoods->where("baidu_dish_id='$dishSkuId'")->save($sqlres);
                        }else{
                            $res=$jdgoods->data($sqlres)->save();
                        }
                    }
                }
            }
        }
        if($res){
            $this->mapping();
            echo 1;
        }else{
            echo 0;
        }
    }

    /**
     * @deprecated
     */
    public function mapping(){
        $url="http://api.open.cater.meituan.com/waimai/dish/mapping";
        $meituan=model("meituan");
        $jdgoods=model("jdgoods");
        $res=$meituan->field(array("epoiid","token"))->select();
        foreach ($res as $k => $val) {//获取门店epoiid，token
            $time=time();
            $appAuthToken=$val['token'];
            $ePoiId=$val['epoiid'];
            $jdgoodsres=$jdgoods->field(array("id","skuid"))->where("goodsasc='2' and shopid='$ePoiId'")->order("skuid")->select();//获取所在门店本地所有菜品基本信息
            $eDishCode=$jdgoodsres['id'];//erp方菜品id
            $dishId=$jdgoodsres['skuid'];//美团菜品id
            foreach ($jdgoodsres as $key => $value) {
                $skuid=$value['skuid'];
                $id=$value['id'];
                $baidu_dish_id=$jdgoods->field(array('baidu_dish_id','id'))->where("goodsasc='2' and shopid='$ePoiId' and skuid=$skuid")->select();
                $list=array();
                foreach ($baidu_dish_id as $ke => $valu) {
                    $list[]=['eDishSkuCode'=>$valu['id'],'dishSkuId'=>$valu['baidu_dish_id']];
                }
                $waiMaiDishSkuMappings=$list;
                $arr[]=array('eDishCode'=>$id,'dishId'=>$skuid,'waiMaiDishSkuMappings'=>$waiMaiDishSkuMappings);
                $key_1=$key-1;
                if($jdgoodsres[$key]['skuid']==$jdgoodsres[$key_1]['skuid']){
                    unset($arr[$key]);
                }
            }
            $dishMappings=json_encode($arr);
            $data=array(
                'appAuthToken'=>$appAuthToken,
                'ePoiId'=>$ePoiId,
                'charset'=>'utf-8',
                'timestamp'=>$time,
                'dishMappings'=>$dishMappings
            );
            $sign_url=$url."?timestamp=$time&charset=utf-8&ePoiId=$ePoiId&appAuthToken=$appAuthToken&dishMappings=$dishMappings";
            $sign=model("meituan")->SignKey($sign_url);
            $data['sign']=$sign;
            $check[]=model("meituan")->post($url,$data);
        }
        //dump($check);
    }

    /**
     * @deprecated
     * @return bool
     */
    public function queryCatList(){
        $url="http://api.open.cater.meituan.com/waimai/dish/queryCatList";
        $meituan=model("meituan");
        $meituantype=model("meituantype");
        $res=$meituan->select();
        foreach ($res as $k => $val) {
            $appAuthToken=$val['token'];
            $charset="utf-8";
            $timestamp=time();
            $sign_url=$url."?timestamp=$timestamp&appAuthToken=$appAuthToken&charset=utf-8";
            $sign=model("meituan")->SignKey($sign_url);
            $geturl=$sign_url."&sign=$sign";
            $result[]=curl_get($geturl);
        }
        foreach ($result as $key => $value) {
            $typeArr[$key]=json_decode($value,ture);
            if(isset($typeArr[$key]['error'])){unset($typeArr[$key]);}//删除获取错误的商品分类
        }
        foreach ($typeArr as $k => $v) {
            foreach ($v['data'] as $key => $val) {
                $epoid=$val['ePoiId'];
                $name=$val['name'];
                $type_data=array(
                    'epoid'=>$epoid,
                    'name'=>$name,
                    'sequence'=>$val['sequence'],
                    'timesave'=>time()
                );
                $check=$meituantype->where("epoid='$epoid' and name='$name'")->count();
                if($check){//当存在就保存数据
                    $checksql=$meituantype->where("epoid='$epoid' and name='$name'")->save($type_data);
                }else{//不存在添加数据
                    $checksql=$meituantype->save($type_data);
                }
            }
        }
        if($checksql){//更新成功后删除以前的分类信息；
            $deltime=(time()-60);
            $delsql=$meituantype->where("timesave < '$deltime'")->delete();
            if($delsql){
                return ture;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    //解绑门店
    public function remove(){
        $Meituansql = model('Meituan');
        $meituan=$Meituansql->select();
        foreach ($meituan as $key => $value) {
            $ePoiId = $value['epoiid'];
            $token = $value['token'];
            $time = time();
            $url = "http://api.open.cater.meituan.com/waimai/poi/queryPoiInfo?timestamp=$time&appAuthToken=$token&charset=UTF-8&ePoiIds=$ePoiId";
            $signKey = model("meituan")->SignKey($url);
            $url = $url."&sign=".$signKey;
            $json = curl_get($url);
            $data[$key] = json_decode($json,true);
            $data[$key]['token']= $token;
        }
        foreach ($data as $key => $value) {
            if(isset($value['error'])){
                unset($data[$key]);//清除错误门店信息
            }
        }

        foreach ($data as $k => $val) {
            $appAuthToken=$val['token'];
            $wurl="https://open-erp.meituan.com/releasebinding?&businessId=2&appAuthToken=$appAuthToken";
            $sign=SIGNKEY;
            $data[$k]['url']=$wurl."&signKey=$sign";
        }
        $this->assign("res",$data);
        $this->display();
    }

}